<?php
class PrizeService{
	/*
	$prizes={round1:[p1,p2],round2:[p3] ...}
	 */
	private static $prizes;

	private static $db;

	private static function db(){
		if(!PrizeService::$db){
			PrizeService::$db = new Prize();
		}
		return PrizeService::$db;
	}

	//初始化奖品池
	public static function initPrize(){
		$modPrize = new Prize();
		$modPrize->setParams(array(
			'fields' =>'id,target_round,name, img_url, show_count, win_count',
			'condition' => array(
				'is_del' => 0
			),
		));
		$arrPrizeList = $modPrize->getList();
		$prizes = array();
		foreach ($arrPrizeList as $prize) {
			$round = $prize['target_round'];
			if(!isset($prizes[$round])){
				$prizes[$round] = array();
			}
			$prizes[$round][] = $prize;
		}
		PrizeService::$prizes = $prizes;
	}

	/**
	 * 获取奖品信息
	 * @return [type] [description]
	 */
	public static function getPrizes(){
		$prizes = PrizeService::$prizes;
		if(!$prizes){
			PrizeService::initPrize();
		}
		return PrizeService::$prizes;
	}

	public static function updatePrize($prize){
		return PrizeService::db()->save($prize);
	}

	/**
	 * 通过round获取对应奖品信息
	 * @param  [type]  $round   [round, 局数]
	 * @param  boolean $silence [是否不更新show_count, 默认false(更新)]
	 * @return [type]           [prize 数组]
	 */
	public static function getPrizesByRound($round, $silence = false){
		$prizes = PrizeService::getPrizes();
		$rtn = $prizes[$round];
		if($rtn && !$silence){
			foreach ($rtn as $prize) {
				$prize['show_count'] += 1;
				PrizeService::db()->save($prize);
			}
		}
		return $rtn ? $rtn : array();
	}

	/**
	 * 标记奖品被认领一次
	 * @param  [type] $prize [prize model]
	 * @return [type]        [prizeId]
	 */
	public static function winPrize($prize){
		$prize['win_count'] += 1;
		return PrizeService::updatePrize($prize);
	}
}